package com.youhome.service.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.youhome.common.exception.CustomException;
import com.youhome.common.response.ResultCode;
import com.youhome.service.mapper.BShareGroupHouseMapper;
import com.youhome.service.mapper.BShareGroupMapper;
import com.youhome.service.model.*;

import com.youhome.service.service.BCounselorService;
import com.youhome.service.service.BShareGroupService;
import com.youhome.service.service.BUserService;
import com.youhome.utils.StringUtils;
import org.modelmapper.ModelMapper;
import org.modelmapper.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Created by chen365 on 2017/11/1.
 */

@Repository
public class BShareGroupServiceImpl implements BShareGroupService {
    @Autowired
    private BUserService bUserService;
    @Autowired
    private BShareGroupMapper bShareGroupMapper;
    @Autowired
    private BShareGroupHouseMapper bShareGroupHouseMapper;
    @Autowired
    private BCounselorService bCounselorService;


    @Override
    @Transactional
    public void delete(String id) throws CustomException {
        if (StringUtils.isEmpty(id)) {
            throw new CustomException(ResultCode.ERROR_PARAMETER);
        }
        if (bShareGroupMapper.deleteByPrimaryKey(id) < 1) {
            throw new CustomException(ResultCode.DELETE_FAIL);
        }
        bShareGroupHouseMapper.deleteByShareId(id);
    }

    @Override
    public BShareGroup selectByPrimaryKey(String shareId) throws CustomException {
        BShareGroup shareGroup = bShareGroupMapper.selectByPrimaryKey(shareId);
        if (shareGroup == null) {
            throw new CustomException(ResultCode.DATA_DOES_NOT_EXIST_OR_HAS_BEEN_DELETED);
        }
        List<ListHub> list = bShareGroupHouseMapper.selectHouseByShareId(shareGroup.getShareId());
        shareGroup.setHouses(new ModelMapper().map(list, new TypeToken<List<ListHubList>>() {
        }.getType()));

        return shareGroup;
    }

    @Override
    public PageInfo<BShareGroup> selectByBean(Principal principal, Integer pageNumber, Integer pageSize, Long counselorId, String name) throws CustomException {

        Long userId = principal.getUser().getUserId();

        if (StringUtils.isEmpty(counselorId)) {
            BCounselor counselor = bCounselorService.selectByUserId(userId);
            if (counselor == null) {
                throw new CustomException(ResultCode.DATA_DOES_NOT_EXIST_OR_HAS_BEEN_DELETED);
            }
            counselorId = counselor.getCounselorId();
        }

        if (pageNumber == null || pageNumber < 1) {
            pageNumber = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        PageHelper.startPage(pageNumber, pageSize);
        BShareGroup shareGroup = new BShareGroup();
        shareGroup.setCounselorId(counselorId);
        if (!StringUtils.isEmpty(name)) {
            shareGroup.setName(name);
        }
        List<BShareGroup> list = bShareGroupMapper.selectByBean(shareGroup);
        return new PageInfo<>(list);
    }

    @Override
    public int create(Long counselorId, String shareGroupName) {
        //创建分享组
        BShareGroup shareGroup = new BShareGroup();
        shareGroup.setName(shareGroupName);
        shareGroup.setCounselorId(counselorId);
        shareGroup.setCtime(new Date());
        shareGroup.setStatus(1);

        return bShareGroupMapper.insertSelective(shareGroup);
    }

    @Override
    public BShareGroup create(BShareGroup shareGroup) {
        if (bShareGroupMapper.insertSelective(shareGroup) == 1) {
            return shareGroup;
        }
        return null;
    }

    /**
     * 添加房源到分享组
     *
     * @param shareId 分享组ID
     * @param houseId 房源ID
     * @return
     * @throws CustomException
     */
    @Override
    public BShareGroupHouse addHouseAppendToShareGroup(String shareId, String houseId) throws CustomException {
        if (StringUtils.isEmpty(shareId) || StringUtils.isEmpty(houseId)) {
            throw new CustomException(ResultCode.ERROR_PARAMETER);
        }
        //判断是否已经添加到分享组
        if (existByHouseId(shareId, houseId)) {
            throw new CustomException(ResultCode.EXIST);
        }

        BShareGroupHouse record = new BShareGroupHouse();
        record.setShareId(shareId);
        record.setHouseId(houseId);
        record.setCtime(new Date());

        if (bShareGroupHouseMapper.insertSelective(record) > 0) {
            return record;
        } else {
            throw new CustomException(ResultCode.FAIL);
        }
    }

    @Override
    public List<BShareGroupItem> selectAllByCounselorId(Long counselorId) {
        return bShareGroupMapper.selectAllByCounselorId(counselorId);
    }

    @Override
    public void deleteHouse(String shareId, String houseId) throws CustomException {
        if (StringUtils.isEmpty(houseId)) {
            throw new CustomException(ResultCode.ERROR_PARAMETER);
        }
        BShareGroupHouse record = new BShareGroupHouse();
        record.setShareId(shareId);
        record.setHouseId(houseId);
        if (bShareGroupHouseMapper.deleteByShareIdAndHouseId(record) == 0) {
            throw new CustomException(ResultCode.FAIL);
        }
    }

    @Override
    public boolean existByHouseId(String shareGroupId, String houseId) {
        BShareGroupHouse record = new BShareGroupHouse();
        record.setShareId(shareGroupId);
        record.setHouseId(houseId);
        return bShareGroupHouseMapper.selectExistByShareIdAndHouseId(record) > 0 ? true : false;
    }

    @Override
    public boolean exist(Long counselorId, String groupName) {
        BShareGroup shareGroup = new BShareGroup();
        shareGroup.setCounselorId(counselorId);
        shareGroup.setName(groupName);
        return bShareGroupMapper.selectExistByBean(shareGroup) > 0 ? true : false;
    }

    @Override
    public List<String> selectShareGroupNameByHouseIdAndCounselorId(Long counselorId, String houseId) {
        Map<String, Object> map = new HashMap<>();
        map.put("counselorId", counselorId);
        map.put("houseId", houseId);
        return bShareGroupMapper.selectShareGroupNameByHouseIdAndCounselorId(map);
    }

    @Override
    public int insert(BShareGroup record) {
        record.setCtime(new Date());
        return bShareGroupMapper.insert(record);
    }

    @Override
    public int updateByPrimaryKey(BShareGroup record) {
        record.setUtime(new Date());
        return bShareGroupMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int deleteByShareIdAndCounselorId(BShareGroup bShareGroup) {
        return bShareGroupMapper.deleteByShareIdAndCounselorId(bShareGroup);
    }

    @Override
    public PageInfo<BShareGroup> selectByBean(Integer pageNumber, Integer pageSize, BShareGroup record) {
        if (StringUtils.isEmpty(pageNumber) || pageNumber < 1) {
            pageNumber = 1;
        }
        if (StringUtils.isEmpty(pageSize) || pageSize < 10) {
            pageSize = 10;
        }
        PageHelper.startPage(pageNumber, pageSize);
        List<BShareGroup> bShareGroups = bShareGroupMapper.selectByBean(record);
        return new PageInfo<>(bShareGroups);
    }

    @Override
    public BShareGroup createShareGroup(Principal principal, String shareGroupName) throws CustomException {
        Long userId = principal.getUser().getUserId();

        if (StringUtils.isEmpty(shareGroupName)) {
            throw new CustomException(ResultCode.ERROR_PARAMETER);
        }

        BCounselor counselor = bCounselorService.selectByUserId(userId);
        if (counselor == null) {
            throw new CustomException(ResultCode.DATA_DOES_NOT_EXIST_OR_HAS_BEEN_DELETED);
        }

        Long counselorId = counselor.getCounselorId();

        if (exist(counselorId, shareGroupName)) {
            throw new CustomException(ResultCode.EXIST);
        }
        BShareGroup shareGroup = new BShareGroup();
        shareGroup.setShareId(UUID.randomUUID().toString());
        shareGroup.setName(shareGroupName);
        shareGroup.setCounselorId(counselorId);
        shareGroup.setCtime(new Date());
        shareGroup.setStatus(1);

        if (bShareGroupMapper.insertSelective(shareGroup) > 0) {
            return shareGroup;
        } else {
            throw new CustomException(ResultCode.FAIL);
        }
    }

    @Override
    public List<BShareGroupItem> selectAllShareGroup(Principal principal) throws CustomException {
        Long userId = principal.getUser().getUserId();
        BCounselor counselor = bCounselorService.selectByUserId(userId);
        if (counselor == null) {
            throw new CustomException(ResultCode.DATA_DOES_NOT_EXIST_OR_HAS_BEEN_DELETED);
        }
        Long counselorId = counselor.getCounselorId();
        return bShareGroupMapper.selectAllByCounselorId(counselorId);
    }

    @Override
    public void deleteByShareIdAndCounselorId(String phone, String shareId) throws CustomException {
        if (StringUtils.isEmpty(shareId)) {
            throw new CustomException(ResultCode.ERROR_PARAMETER);
        }
        BUser bUser = bUserService.selectByPhone(phone);
        BCounselor bCounselor = null;
        if (bUser != null) {
            bCounselor = bCounselorService.selectByUserId(bUser.getUserId());
        }
        if (bCounselor == null) {
            throw new CustomException(ResultCode.LAND_EXPIRATION);
        }

        BShareGroup bShareGroup = new BShareGroup();
        bShareGroup.setShareId(shareId); //分享组Id
        bShareGroup.setCounselorId(bCounselor.getCounselorId()); //顾问ID

        if (bShareGroupMapper.deleteByShareIdAndCounselorId(bShareGroup) == 0) {
            throw new CustomException(ResultCode.FAIL);
        }
    }

    @Override
    public void updateByBean(String phone, BShareGroup bShareGroup) throws CustomException {
        BUser bUser = bUserService.selectByPhone(phone);
        BCounselor bCounselor = null;
        if (bUser != null) {
            bCounselor = bCounselorService.selectByUserId(bUser.getUserId());
        }
        if (bCounselor == null) {
            throw new CustomException(ResultCode.LAND_EXPIRATION);
        }
        bShareGroup.setCounselorId(bCounselor.getCounselorId()); //顾问ID
        bShareGroup.setUtime(new Date());
        if (bShareGroupMapper.updateByPrimaryKeySelective(bShareGroup) == 0) {
            throw new CustomException(ResultCode.FAIL);
        }
    }

    @Override
    public void addShareGroupHits(String shareId) throws CustomException {
        if (bShareGroupMapper.updateHitsByShareId(shareId) < 1) {
            throw new CustomException(ResultCode.FAIL);
        }
    }
}
